package com.roundarch.www.ui;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.roundarch.www.model.Comment;
import com.roundarch.www.model.Post;
import com.roundarch.www.model.User;
import com.roundarch.www.util.StringUtils;
import com.roundarch.www.util.propertyeditor.EntityPropertyEditor;

@Controller
@RequestMapping("/comment")
public class CommentController extends AbstractEntityController<Comment> {

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(
			@Valid @ModelAttribute("entity") Comment entity,
			BindingResult result,
			Model model,
			HttpServletRequest request) {

		if (result.hasErrors()) {
			// TODO set 'flash' to error
			buildEditModel(entity, model,request);
			return StringUtils.joinPath(getRootRequestMapping(), "/post/show?id="+entity.getPost().getId());
		}
		
		getEntityService().save(entity);
		
		return "redirect:/post/show?id="+entity.getPost().getId();
	}
	
	@Override
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		super.initBinder(binder);

		binder.registerCustomEditor(User.class,	new EntityPropertyEditor<User>(getEntityService(),User.class));
		binder.registerCustomEditor(Post.class,	new EntityPropertyEditor<Post>(getEntityService(),Post.class));
		
	}
	
}
